package com.baoyanghui.common;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.security.NoSuchAlgorithmException;
import java.util.List;
import java.util.Map;

import net.sf.json.JSONObject;

import com.baoyanghui.config.Configs;

public class InterfaceAccess {
	private static final String InterfaceHost = "http://localhost:8080/Car";
	public static final String InterfaceContext = "/Car";
	
	public static JSONObject callInterface(String method, Map<String, String> paramMap) throws IOException {
		String result = "";
		String param = "";
		List<String> keys = Utils.sortKeys(paramMap.keySet());
		for (String key : keys) {
			if (paramMap.get(key) == null) {
				continue;
			}
			param += ("".equals(param) ? "" : "&") +  key + "=" + URLEncoder.encode(paramMap.get(key), "UTF-8");
		}
		try {
			param += "&sign=" + Utils.md5(param + Configs.PUBLIC_KEY);
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		}

		URL url = new URL(InterfaceHost + method);
		URLConnection conn = url.openConnection();
		conn.setDoOutput(true);
		OutputStreamWriter out = new OutputStreamWriter(conn.getOutputStream(), "UTF-8");
		out.write(param);
		out.flush();
		out.close();

		BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
		String res = br.readLine();
		while (res != null) {
			result += res;
			res = br.readLine();
		}
		
		return JSONObject.fromObject(result);
	}
}
